'use strict'

define(['jquery', 'bootstrap', 'shiftform', 'validate', 'validate.en', 'select2',
        'datetimepicker', 'datetimepickerCN', 'koala-search', 'modalSearch'], function ($) {
  
  return {
  
    init: function (data) {
      this.data = data;
      this.editInfo();
    },
    
    editInfo: function() {
      var that = this;
      
      $(document).on('shown.bs.modal', '#edit-info', function(e) {
        
        that.existBrandCNCodeFunc();
        
        $(e.currentTarget).find('form[data-validate="true"]').bt_validate()  //bind validate

        var $form = $(e.currentTarget).find("form")                          //bind shiftform
        $form.shiftform({
          beforeSubmit: function (el) {
            $form.trigger("validate.ajax.submit");
            return $.bt_validate.result[$.bt_validate.form_id];
          }
        });
        
      })
      
      $(document).on('hidden.bs.modal', '#edit-info', function(e) {
        $('.month').datetimepicker('remove'); 
      })
      
    },
    
    existBrandCNCodeFunc: function() {
      
      var that = this;
      var $btnSubmit = $('button.btn-submit');
      
      // 校验挂车中文车牌号是否存在
      $(document).on('mouseleave', 'input[name="brandCNCode"]', function(e) {
        
        e.stopPropagation();
        
        var $brandCNCode = $('input[name="brandCNCode"]');
        var brandCNCode = $brandCNCode.val().trim();
        if (!brandCNCode) return;
        if (brandCNCode == that.data.brandCNCode) {
          $btnSubmit.prop('disabled', false);
          return;
        }
          
        $.ajax({
          'url': window.__CTX__.root + "/trailers/exist",
          'data': {
            'brandCNCode': brandCNCode
          }
        }).done(function(res){
          
          res = typeof res === 'String' ? JSON.parse(res) : res;
          if (res.data.exist) {
            $brandCNCode.show_err_tooltip('该挂车中文牌号已存在！');
            $btnSubmit.prop('disabled', true);
            return false;
          }
          
          $btnSubmit.prop('disabled', false);
          
        }).fail(function(){
          $brandCNCode.show_err_tooltip('查询挂车中文牌号失败！');
          $btnSubmit.prop('disabled', true);
        });

      });
      
    }

  }
})